package gemini.castor.ui.client.page.widget.productlist;

import gemini.basic.model.Product;
import gemini.castor.ui.client.page.widget.productpreview.ProductPreviewEvent;
import gemini.castor.ui.client.page.widget.productpreview.ProductPreviewHandler;
import gemini.castor.ui.client.page.widget.productpreview.ProductPreviewWidget;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.HasHandlers;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Panel;

public class ProductListWidget extends Composite implements HasHandlers{

	@UiTemplate("ProductListWidget.ui.xml")
	interface MyUiBinder extends UiBinder<Panel, ProductListWidget> {
	}

	private static final MyUiBinder binder = GWT.create(MyUiBinder.class);

	public ProductListWidget() {
		initWidget(binder.createAndBindUi(this));
	}

	@UiField
	HorizontalPanel content;
	
	public void loadData(List<Product> products){
		content.clear();
		for (final Product pr : products) {
			ProductPreviewWidget prPreview = new ProductPreviewWidget();
			prPreview.loadData(pr);
			prPreview.addProductPreviewHandler(new ProductPreviewHandler() {
				
				@Override
				public void onSelected(ProductPreviewEvent productPreviewEvent) {
					ProductListEvent event = new ProductListEvent(
							ProductListEvent.ForwardType.SELECT_PRODUCT);
					event.setSelectedProduct(pr);
					fireEvent(event);
				}
			});
			
			content.add(prPreview);
		}
	}
	
	public void addProductListHandler(ProductListHandler handler){
		this.addHandler(handler, ProductListEvent.getType());
	}
}
